<?php

namespace app\admin\controller\template;

use app\admin\model\template\Order;
use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;

/**
 * 模板上架审核管理
 *
 * @icon fa fa-circle-o
 */
class Review extends Backend
{

    /**
     * Review模型对象
     * @var \app\admin\model\template\Review
     */
    protected $model = null;
    private \app\admin\model\template\Template $templateModel;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\template\Review;
        $this->templateModel = new \app\admin\model\template\Template();

        $statusList = $this->model->getStatusList();
        $this->view->assign("statusList", $statusList);


        $categoryModel = new \app\admin\model\template\TemplateCategory;
        $categoryNameList = $categoryModel->where('pid','>',0)->column('name','id');

        $this->view->assign('categoryNameList', $categoryNameList);
        $this->assignconfig('categoryNameList', $categoryNameList);

        $groupNameList = $categoryModel->where('pid',0)->column('name','id');
        $this->view->assign('groupNameList', $groupNameList);
        $this->assignconfig('groupNameList', $groupNameList);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    public function edit($ids = null)
    {
        $review = $this->model->get(['id' => $ids]);
        if (is_null($review)) throw new Exception('当前产品不在审核表中');
        $row = \app\admin\model\template\Template::get(['id' => $review->template_id]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params) {
                $user = $this->auth->getUserInfo();
                $now = time();
                if ($params['status']) {
                    if ($params['status'] == 2) {
                        if (!$params['reason']) {
                            $this->error('请填写驳回原因');
                        }
                        $row->reason = $params['reason'];
                        $review->reason = $params['reason'];
                    } elseif ($params['status'] == 1) {
                        $row->status = 1;

                        $row->product_name = $review->product_name;
                        $row->name = $review->name;
                        $row->thumbnail = $review->thumbnail;
                        $row->price = $review->price;
                        $row->description = $review->description;
                        $row->category_id = $review->category_id;
                        $row->group_id = $review->group_id;
                    }
                    $row->checktime = $now;
                    $row->check_user = $user['nickname'] ?: $user['username'];
                    $row->check_status = $params['status'];

                    $review->status = $row->check_status;
                    $review->check_user =  $row->check_user;
                    $review->checktime = $row->checktime;
                } else {
                    $row->checktime = null;
                    $review->checktime = null;
                }

//                $new_order = [];
//                if ($row->check_status == 1) {
//                    $company_id = $row->user()->value('company_id');
//                    $row->product_name = $review->product_name;
//                    $row->name = $review->name;
//                    $row->thumbnail = $review->thumbnail;
//                    $row->price = $review->price;
//                    $row->description = $review->description;
//                    if(!Order::where('user_id', $row->user_id)->where( 'template_id', $row->id)->find()) {
//                        $new_order = [
//                            'company_id' => $company_id,
//                            'order_sn' =>  generateOrderId('T'),
//                            'user_id' => $row->user_id,
//                            'template_id' => $row->id,
//                            'pay_state' => 1,
//                            'type' => 1,
//                            'price' => 0,
//                            'platform_service_fee' => 0,
//                            'agency_account_fee' => 0,
//                            'data_depository_fee' => 0,
//                            'information_service_fee' => 0,
//                            'author_commission_ratio' => 0,
//                            'createtime' => $now
//                        ];
//                    }
//                }

                Db::startTrans();
                try {

                    $num = $review->save();
                    if (!$num) throw new Exception('审核失败');
                    $num = $row->save();
                    if (!$num) throw new Exception("审核失败");

//                    if ($row->check_status == 1 && $new_order) {
//                        Order::create($new_order);
//                    }
                    Db::commit();
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error('服务错误');
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success('请求成功');
            }
            $this->error();
        }
        $this->view->assign("row", $review);
        return $this->view->fetch();
    }



    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            $userNameList = [];
            $productNameList= [];
            $this->model->with(['user' => function ($query) {
                $query->field('id,nickname');
            },'product' => function ($query) {
                $query->field('id,name');
            }])->field('user_id,product_id')->select()->each(function ($item) use (&$userNameList,&$productNameList) {
                if ($item->user) {
                    $userNameList[$item['user_id']] = $item->user->nickname;
                }
                if ($item->product) {
                    $productNameList[$item['product_id']] = $item->product->name;
                }
            });
            $userNameList[0] = '无';
            $this->assignconfig('userNameList', $userNameList);
            $this->assignconfig('productNameList', $productNameList);
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $data = $this->model->where($where)->order($sort, $order)->paginate($limit);
        $result = ['total' => $data->total(), 'rows' => $data->items()];
        return json($result);
    }


}
